<?php

namespace App\Console\Commands;

use App\Enum\OrderDyplsEnum;
use App\Models\OrderDyplsModel;
use App\Models\OrderExtendModel;
use App\Models\OrderModel;
use App\Services\OrderService;
use Illuminate\Console\Command;

class orderCreatedCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:created-task {num_per_each?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '订单生成后的一些异步任务- Deprecated';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws \Exception
     */
    public function handle(): int
    {
        return 0;
        /**
        $dyplsEnabled = env('ALIYUN_DYPLS_ENABLED',true);
        while(1) {
            $second = date('s');
            $sleepRatio = 1;
            $sleep = 1;

            if ($second >= 55) {
                $this->info("second = $second, wait for next time.");
                break;
            }else  $this->info("second = $second, keep going.");
            $num = $this->argument('num_per_each') ?? 1;
            $orderId = OrderExtendModel::query()->max('order_id' );
            if( empty($orderId) ) $orderId = 0;

            $rows = OrderModel::query()->fromQuery(
                'SELECT o.id,o.order_no,o.created_at FROM  sxcx_orders AS o WHERE o.id > '.$orderId.' ORDER BY o.id ASC LIMIT '.$num
            )->toArray();
            if( !empty($rows) ){
                foreach( $rows as $row){
                    // 写入订单的虚拟号
                    $dyplsEnabled && OrderDyplsModel::query()->create([
                        'order_id'=> $row['id'],
                        'order_no'=> $row['order_no'],
                        'status'    => OrderDyplsEnum::STATUS_UN_USE
                    ]);
                    // 订单异步的补偿机制
                    //$this->_handleExtend($row['id'], $row['created_at']);

                }
            }else $sleepRatio = 3;

            sleep($sleep*$sleepRatio);
        }
        //
        return 0;
         */
    }

    /**
     * @throws \Exception
     */
    private function _handleExtend($orderId, $createdAt)
    {
        if( time() - strtotime($createdAt) > 60 * env('ORDER_EXTEND_COMPENSATE_TIME',1) ){
            $orderInfo = OrderModel::query()->find($orderId);
            OrderService::handleStatic($orderInfo);
        }
    }
}
